package com.yuheadline.article.service.impl;

import com.aliyun.oss.OSS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dust.yuheadline.common.aliyun.oss.OssFileUploader;
import com.dust.yuheadline.common.aliyun.utils.AliOssProperties;
import com.dust.yuheadline.common.exception.CustomException;
import com.dust.yuheadline.common.utils.ResponseCode;
import com.dust.yuheadline.common.utils.Result;
import com.yuheadline.article.mapper.ArticleImageMapper;
import com.yuheadline.article.service.ArticleImageService;
import com.yuheadline.article.util.ThreadLocalUtil;
import com.yuheadline.model.article.domain.ArticleImage;
import com.yuheadline.model.article.dto.SaveArticleImgDto;
import com.yuheadline.model.article.enums.ImageTypeEnum;
import com.yuheadline.model.article.vo.SaveArticleImageVo;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

/**
 * @author 高翔宇
 * @since 2025/4/19 周六 17:19
 */
@Service
@RequiredArgsConstructor
public class ArticleImageServiceImpl extends ServiceImpl<ArticleImageMapper, ArticleImage> implements ArticleImageService {
    private final OssFileUploader ossFileUploader;
    private final ArticleImageMapper articleImageMapper;
    private final OSS oss;
    private final AliOssProperties aliOssProperties;

    /**
     * 根据文章id删除图片
     */
    @Override
    public void deleteArticleImageByArticleId(Long articleId) {
        articleImageMapper.selectList(new LambdaQueryWrapper<ArticleImage>().eq(ArticleImage::getArticleId, articleId)).forEach(image -> {
            oss.deleteObject(aliOssProperties.getBucketName(), image.getObjectName());
        });
        articleImageMapper.delete(new LambdaQueryWrapper<ArticleImage>().eq(ArticleImage::getArticleId, articleId));
    }

    @Override
    public Result<SaveArticleImageVo> saveArticleImage(MultipartFile imageFile, SaveArticleImgDto saveArticleImgDto) {
        try {
            // 上传图片到阿里云OSS
            byte[] bytes = imageFile.getBytes();
            String originalFilename = imageFile.getOriginalFilename();
            String objectName;
            if (originalFilename != null) {
                objectName = UUID.randomUUID() + originalFilename.substring(imageFile.getOriginalFilename().lastIndexOf("."));
            } else {
                objectName = UUID.randomUUID() + ".png";
            }
            String url = ossFileUploader.uploadAndGetPermanentUrl(bytes, objectName);
            Long userId = ThreadLocalUtil.getUserId();
            if (userId == null) {
                throw new CustomException(ResponseCode.NOT_LOGIN);
            }
            ArticleImage image = ArticleImage.builder()
                    .userId(userId)
                    .imageUrl(url)
                    .objectName(objectName)
                    .type(ImageTypeEnum.getByCode(saveArticleImgDto.getType())).build();
            Long articleId = saveArticleImgDto.getArticleId();
            if (articleId != null && articleId != -1) {
                image.setArticleId(articleId);
            } else {
                image.setTempArticleId(saveArticleImgDto.getTempArticleId());
            }
            // 插入并获取id
            articleImageMapper.insert(image);
            return new Result<SaveArticleImageVo>().success(SaveArticleImageVo.builder()
                    .id(image.getId())
                    .imageUrl(url).build(), "上传成功");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 保存文章图片，接受url
     */
    @Override
    public Result<SaveArticleImageVo> saveArticleImageUrl(SaveArticleImgDto saveArticleImgDto) {
        Long userId = ThreadLocalUtil.getUserId();
        if (userId == null) {
            throw new CustomException(ResponseCode.NOT_LOGIN);
        }
        String imageUrl = saveArticleImgDto.getImageUrl();
        ArticleImage image = ArticleImage.builder()
                .userId(userId)
                .imageUrl(imageUrl)
                .type(ImageTypeEnum.getByCode(saveArticleImgDto.getType()))
                .imageName(saveArticleImgDto.getImageName()).build();
        Long articleId = saveArticleImgDto.getArticleId();
        if (articleId != null && articleId != -1) {
            image.setArticleId(articleId);
        } else {
            image.setTempArticleId(saveArticleImgDto.getTempArticleId());
        }
        // 插入并获取id
        articleImageMapper.insert(image);
        return new Result<SaveArticleImageVo>().success(SaveArticleImageVo.builder()
                .id(image.getId())
                .imageUrl(imageUrl).build(), "上传成功");
    }
}
